package org.linlinjava.litemall.admin.service.order_manage;

import afu.org.checkerframework.checker.igj.qual.I;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.models.auth.In;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.json.JSONArray;
import org.linlinjava.litemall.admin.dto.OnlineServiceInfoDto;
import org.linlinjava.litemall.admin.enums.AdminErrorCode;
import org.linlinjava.litemall.admin.form.CommodityAddRegualrForm;
import org.linlinjava.litemall.admin.form.CommodityAddRegualrListForm;
import org.linlinjava.litemall.admin.util.BcryptUtil;
import org.linlinjava.litemall.admin.vo.locks.Address;
import org.linlinjava.litemall.admin.vo.online_service.*;
import org.linlinjava.litemall.admin.vo.order_manage.CommodityDetailRegualrForm;
import org.linlinjava.litemall.admin.vo.order_manage.CommodityDetailRegualrListForm;
import org.linlinjava.litemall.admin.vo.order_manage.CommodityDetailRegualrNameForm;
import org.linlinjava.litemall.admin.vo.order_manage.CommodityDetailRegualrValueForm;
import org.linlinjava.litemall.admin.vo.shop.ClassiftChilden;
import org.linlinjava.litemall.admin.vo.shop.ClassifyParent;
import org.linlinjava.litemall.admin.vo.wechat.GroupMessage;
import org.linlinjava.litemall.admin.vo.wechat.UpdateGroupMessage;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.config.ServerAddress;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.dao.order_manage.AgedmallOnlineMapper;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.jsonfield.LitemallGoodsProductSpecification;
import org.linlinjava.litemall.db.util.GoodsProductConstant;
import org.linlinjava.litemall.db.util.GoodsSpecificationConstant;
import org.linlinjava.litemall.db.vo.online.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;

import static com.alibaba.fastjson.JSON.toJSONString;

/**
 * @author wj
 * @date 2021/8/6 18:02
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AgedmallOnlineServices {

    @Resource
    private AgedmallOnlineServiceMapper agedmallOnlineServiceMapper;

    @Resource
    private AgedmallOnlineMapper agedmallOnlineMapper;

    @Resource
    private AgedmallOnlineServiceProductMapper agedmallOnlineServiceProductMapper;

    @Resource
    private AgedmallOnlineCityMapper agedmallOnlineCityMapper;

    @Resource
    private AgedmallOnlineCityProductMapper agedmallOnlineCityProductMapper;

    @Resource
    private AgedmallDepartmentMapper agedmallDepartmentMapper;

    @Resource
    private LitemallUserMapper litemallUserMapper;

    @Resource
    private AgedmallAgentMapper agedmallAgentMapper;

    @Resource
    private AgedmallTimeTemplateMapper agedmallTimeTemplateMapper;

    @Resource
    private AgedmallDoctorInfoMapper agedmallDoctorInfoMapper;

    @Resource
    private AgedmallShopService agedmallShopService;

    @Resource
    private LitemallRegionMapper litemallRegionMapper;

    @Resource
    private AgedmallClassifyMapper agedmallClassifyMapper;

    @Resource
    private LitemallGoodsMapper litemallGoodsMapper;

    @Resource
    private AgedmallGoodsSpecificationInfoMapper agedmallGoodsSpecificationInfoMapper;

    @Resource
    private LitemallGoodsSpecificationMapper litemallGoodsSpecificationMapper;

    @Resource
    private LitemallGoodsProductMapper litemallGoodsProductMapper;

    @Resource
    private AgedmallWechatGroupNumberMapper agedmallWechatGroupNumberMapper;

    @Resource
    private AgedmallWechatGroupMapper agedmallWechatGroupMapper;

    @Resource
    private ServerAddress serverAddress;


    public Object getResultMessage(String result){
        JSONObject jsonObject = JSON.parseObject(result);
        String msg =(String)jsonObject.get("errmsg") ;
        int code =(int)jsonObject.get("errcode") ;
        if(code!=0){
            return ResponseUtil.fail(code,msg);
        }
        else {
            return ResponseUtil.ok();
        }
    }

    public void saveOnlineServiceProduct(List<CommodityAddRegualrForm> regualr ,Integer onlineId){
        if (CollectionUtils.isNotEmpty(regualr)) {
            // 已保存的规格和其id
            Map<String, Integer> savedRegMap = new HashMap<>();
            for (CommodityAddRegualrForm commodityAddRegualrForm : regualr) {
                if (null != commodityAddRegualrForm.getProductId()) {
                    LitemallGoodsProduct product = litemallGoodsProductMapper.selectByPrimaryKey(commodityAddRegualrForm.getProductId());
                    if (null != product) {
                        product.setPrice(commodityAddRegualrForm.getCost());
                        product.setOriginalPrice(commodityAddRegualrForm.getOrginalPrice());
                        product.setDeposit(commodityAddRegualrForm.getDeposit());
                        product.setUrl(commodityAddRegualrForm.getPicture());
                        product.setWeight(commodityAddRegualrForm.getWeight());
                        product.setUpdateTime(LocalDateTime.now());
                        litemallGoodsProductMapper.updateByPrimaryKey(product);
                    }
                } else {
                    List<CommodityAddRegualrListForm> regualrs = commodityAddRegualrForm.getRegualrs();
                    // 规格组合
                    List<LitemallGoodsProductSpecification> specList = new ArrayList<>();
                    for (CommodityAddRegualrListForm listForm : regualrs) {
                        // name为规格类型，value为具体规格，没保存过进行保存
                        if (!savedRegMap.containsKey(listForm.getName())) {
                            AgedmallGoodsSpecificationInfo specificationInfo = new AgedmallGoodsSpecificationInfo();
                            specificationInfo.setGoodsId(onlineId);
                            specificationInfo.setSpecName(listForm.getName());
                            specificationInfo.setType(GoodsSpecificationConstant.TYPE_ONLINE);
                            specificationInfo.setAddTime(LocalDateTime.now());
                            specificationInfo.setDeleted(false);
                            agedmallGoodsSpecificationInfoMapper.insertSelective(specificationInfo);
                            savedRegMap.put(listForm.getName(), specificationInfo.getId());
                        }
                        if (!savedRegMap.containsKey(listForm.getName() + "@#$" + listForm.getValue())) {
                            LitemallGoodsSpecification specification = new LitemallGoodsSpecification();
                            specification.setGoodsId(onlineId);
                            specification.setSpecification(listForm.getName());
                            specification.setValue(listForm.getValue());
                            specification.setParentId(savedRegMap.get(listForm.getName()));
                            specification.setAddTime(LocalDateTime.now());
                            specification.setDeleted(false);
                            litemallGoodsSpecificationMapper.insertSelective(specification);
                            savedRegMap.put(listForm.getName() + "@#$" + listForm.getValue(), specification.getId());
                        }
                        LitemallGoodsProductSpecification spec = new LitemallGoodsProductSpecification();
                        spec.setId(savedRegMap.get(listForm.getName() + "@#$" + listForm.getValue()));
                        spec.setName(listForm.getValue());
                        spec.setInfoId(savedRegMap.get(listForm.getName()));
                        spec.setInfoName(listForm.getName());
                        specList.add(spec);
                    }
                    // 保存规格商品
                    LitemallGoodsProduct product = new LitemallGoodsProduct();
                    product.setGoodsId(onlineId);
                    product.setSpecifications(JSON.toJSONString(specList));
                    product.setPrice(commodityAddRegualrForm.getCost());
                    product.setOriginalPrice(commodityAddRegualrForm.getOrginalPrice());
                    product.setDeposit(commodityAddRegualrForm.getDeposit());
                    product.setUrl(commodityAddRegualrForm.getPicture());
                    product.setWeight(commodityAddRegualrForm.getWeight());
                    product.setType(GoodsProductConstant.TYPE_ONLINE);
                    product.setAddTime(LocalDateTime.now());
                    product.setDeleted(false);
                    litemallGoodsProductMapper.insertSelective(product);
                }
            }
        }
    }


    public Object addOnlineService(AddOnlineServiceVo addOnlineServiceVo){
        AgedmallOnlineService agedmallOnlineService;
        if(addOnlineServiceVo.getServiceId()!=null){
            agedmallOnlineService=agedmallOnlineServiceMapper.selectByPrimaryKey(addOnlineServiceVo.getServiceId());
            AgedmallOnlineServiceProductExample productExample=new AgedmallOnlineServiceProductExample();
            productExample.or().andOnlineServiceIdEqualTo(addOnlineServiceVo.getServiceId()).andDeletedEqualTo(false);
            //删除之前的规格
            agedmallOnlineServiceProductMapper.deleteByExample(productExample);
//            // 删除规格表
//            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
//            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(addOnlineServiceVo.getServiceId());
//            litemallGoodsSpecificationMapper.logicalDeleteByExample(litemallGoodsSpecificationExample);
//            AgedmallGoodsSpecificationInfoExample infoExample=new AgedmallGoodsSpecificationInfoExample();
//            infoExample.or().andDeletedEqualTo(false).andGoodsIdEqualTo(addOnlineServiceVo.getServiceId());
//            agedmallGoodsSpecificationInfoMapper.logicalDeleteByExample(infoExample);
//            // 删除规格商品表
//            LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
//            litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
//                    .andGoodsIdEqualTo(addOnlineServiceVo.getServiceId());
//            litemallGoodsProductMapper.logicalDeleteByExample(litemallGoodsProductExample);
        }
        else{
            agedmallOnlineService=new AgedmallOnlineService();
            agedmallOnlineService.setStat(1);
            agedmallOnlineService.setAddTime(LocalDateTime.now());
        }
        agedmallOnlineService.setName(addOnlineServiceVo.getServiceName());
        agedmallOnlineService.setContent(addOnlineServiceVo.getServiceJj());
        agedmallOnlineService.setServiceImage(toJSONString(addOnlineServiceVo.getServiceImg()));
        agedmallOnlineService.setServiceVideo(addOnlineServiceVo.getServiceVideo());
        agedmallOnlineService.setClassifyId(addOnlineServiceVo.getServiceType());
        agedmallOnlineService.setTagId(addOnlineServiceVo.getServiceLabel());
        if(addOnlineServiceVo.getJoinAdv() != null){
            agedmallOnlineService.setIsExtension(addOnlineServiceVo.getJoinAdv().getJoinState());
            if(addOnlineServiceVo.getJoinAdv().getJoinState()!=0){
                agedmallOnlineService.setExtensionType(addOnlineServiceVo.getJoinAdv().getJoinValue());
                agedmallOnlineService.setExtensionMoney(addOnlineServiceVo.getJoinAdv().getJoinValue()==0?
                addOnlineServiceVo.getJoinAdv().getJoinPercent():addOnlineServiceVo.getJoinAdv().getJoinFix());
            }
        }
        /*if(addOnlineServiceVo.getJoinAdv().getJoinState()!=0){
            agedmallOnlineService.setExtensionType(addOnlineServiceVo.getJoinAdv().getJoinValue());
            agedmallOnlineService.setExtensionMoney(addOnlineServiceVo.getJoinAdv().getJoinValue()==0?
             addOnlineServiceVo.getJoinAdv().getJoinPercent():addOnlineServiceVo.getJoinAdv().getJoinFix());
        }*/
        agedmallOnlineService.setCostPrice(BigDecimal.valueOf(addOnlineServiceVo.getCost()));
        agedmallOnlineService.setOriginalPrice(BigDecimal.valueOf(addOnlineServiceVo.getOriginalPrice()));
        agedmallOnlineService.setShareContent(addOnlineServiceVo.getShareDescript());
        agedmallOnlineService.setServiceDepartment(addOnlineServiceVo.getDepartment().toString());
        agedmallOnlineService.setAppointmentNotice(addOnlineServiceVo.getServiceNotice());
        agedmallOnlineService.setServicePath(addOnlineServiceVo.getServiceProcess());
        agedmallOnlineService.setServiceTime(toJSONString(addOnlineServiceVo.getTimeList()));
        agedmallOnlineService.setAppointmentDay(addOnlineServiceVo.getAppointTime());
        agedmallOnlineService.setBusId(addOnlineServiceVo.getShopId());
        if(addOnlineServiceVo.getDescriptionList() != null){
            agedmallOnlineService.setDescriptionList(addOnlineServiceVo.getDescriptionList()==null?null:addOnlineServiceVo.getDescriptionList().toString());
        }
        agedmallOnlineService.setDoctorDivided(addOnlineServiceVo.getDoctorDivided()==null?100:addOnlineServiceVo.getDoctorDivided());
        if(addOnlineServiceVo.getServiceId()!=null){
            agedmallOnlineServiceMapper.updateByPrimaryKeySelective(agedmallOnlineService);
        }
        else{
            agedmallOnlineServiceMapper.insertSelective(agedmallOnlineService);
        }
        List<CommodityAddRegualrForm> serviceSpec = addOnlineServiceVo.getServiceSpec();
        List<AgedmallOnlineServiceProduct> list=new ArrayList<>();
        if(serviceSpec.size() > 0){
            //规格表
            for (int i = 0; i < serviceSpec.size(); i++) {
                AgedmallOnlineServiceProduct product=new AgedmallOnlineServiceProduct();
                product.setOnlineServiceId(agedmallOnlineService.getId());
                product.setSpecifications(toJSONString(serviceSpec.get(i)));
                product.setCostPrice(serviceSpec.get(i).getCost());
                product.setOriginalPrice(serviceSpec.get(i).getOrginalPrice());
                product.setPictureUrl(serviceSpec.get(i).getPicture());
                product.setAddTime(LocalDateTime.now());
                list.add(product);
            }
        }
        //规格插入GoodsProduct
        saveOnlineServiceProduct(serviceSpec,agedmallOnlineService.getId());

        agedmallOnlineMapper.insertOnlineProductBatch(list);
        return ResponseUtil.ok();
    }


    public Object deleteService(List<Long> idList){
        AgedmallOnlineCityExample onlineCityExample=new AgedmallOnlineCityExample();
        onlineCityExample.or().andOnlineServerIdIn(idList).andDeletedEqualTo(false);
        AgedmallOnlineCity agedmallOnlineCity = agedmallOnlineCityMapper.selectOneByExample(onlineCityExample);
        if(ObjectUtil.isNotNull(agedmallOnlineCity)){
            return ResponseUtil.fail(1202,"当前服务已绑定服务城市");
        }
        AgedmallOnlineServiceExample onlineServiceExample=new AgedmallOnlineServiceExample();
        List<Integer> intIdList=new ArrayList<>();
        idList.forEach( id -> intIdList.add(id.intValue()));
        onlineServiceExample.or().andIdIn(intIdList);
        agedmallOnlineServiceMapper.logicalDeleteByExample(onlineServiceExample);
        return ResponseUtil.ok();
    }

    public Integer serverStateChange(String stateName){
        switch (stateName){
            case "saling":
                return 1;
            case "notSold":
                return 0;
            case "allService":
            default:
                return null;
        }
    }


    public Object onlineServiceList(ServiceListVo serviceListVo){
        Page page=PageHelper.startPage(serviceListVo.getPage(),serviceListVo.getLimit());
        List<OnlineServiceDto> onlineServiceList = agedmallOnlineMapper.getOnlineServiceList(serviceListVo.getShopId(),serviceListVo.getServiceTypeId(),
                serviceListVo.getServiceSubTypeId(),serviceListVo.getServiceName(),serviceListVo.getServiceState()==null?null:serverStateChange(serviceListVo.getServiceState()));
        int sort=1;
        if(serviceListVo.getServiceTypeId()!=null){
            sort=agedmallClassifyMapper.selectByPrimaryKey(serviceListVo.getServiceTypeId()).getShowSort();
        }
        else if(serviceListVo.getServiceSubTypeId()!=null){
            sort=agedmallClassifyMapper.selectByPrimaryKey(serviceListVo.getServiceTypeId()).getShowSort();
        }
        if(sort==0){
            onlineServiceList.sort((o1, o2) -> o2.getId() > o1.getId() ? -1 : 1);
        }
        for (int i = 0; i < onlineServiceList.size(); i++) {
            AgedmallOnlineServiceProductExample productExample=new AgedmallOnlineServiceProductExample();
            productExample.or().andOnlineServiceIdEqualTo(onlineServiceList.get(i).getId()).andDeletedEqualTo(false);
            List<AgedmallOnlineServiceProduct> agedmallOnlineServiceProducts = agedmallOnlineServiceProductMapper.selectByExample(productExample);
            onlineServiceList.get(i).setProductList(agedmallOnlineServiceProducts);
            OnlineProductSpec onlineProductSpec=onlineServiceProductAssemble(onlineServiceList.get(i).getId());
            List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm> regualrList=new ArrayList<>();
            List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm> regualrCombo=new ArrayList<>();
            regualrList=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrList()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm.class);
            regualrCombo=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrCombo()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm.class);
            onlineServiceList.get(i).setRegualrList(regualrList);
            onlineServiceList.get(i).setRegualrCombo(regualrCombo);
        }
        Map<String,Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",onlineServiceList);
        return ResponseUtil.ok(map);
    }


    public OnlineProductSpec onlineServiceProductAssemble(Integer onlineId){

        OnlineProductSpec onlineProductSpec=new OnlineProductSpec();
        // 组装常规规格
        List<CommodityDetailRegualrNameForm> regualrList = new ArrayList<>();

        AgedmallGoodsSpecificationInfoExample agedmallGoodsSpecificationInfoExample = new AgedmallGoodsSpecificationInfoExample();
        agedmallGoodsSpecificationInfoExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(onlineId)
                .andTypeEqualTo(GoodsSpecificationConstant.TYPE_ONLINE);
        List<AgedmallGoodsSpecificationInfo> goodsSpecificationInfoList = agedmallGoodsSpecificationInfoMapper.selectByExample(agedmallGoodsSpecificationInfoExample);
        for (AgedmallGoodsSpecificationInfo specificationInfo : goodsSpecificationInfoList) {
            CommodityDetailRegualrNameForm commodityDetailRegualrNameForm = new CommodityDetailRegualrNameForm();
            commodityDetailRegualrNameForm.setSpecInfoId(specificationInfo.getId());
            commodityDetailRegualrNameForm.setName(specificationInfo.getSpecName());

            List<CommodityDetailRegualrValueForm> valueList = new ArrayList<>();
            LitemallGoodsSpecificationExample litemallGoodsSpecificationExample = new LitemallGoodsSpecificationExample();
            litemallGoodsSpecificationExample.createCriteria().andDeletedEqualTo(false)
                    .andGoodsIdEqualTo(onlineId)
                    .andParentIdEqualTo(specificationInfo.getId());
            List<LitemallGoodsSpecification> specificationList = litemallGoodsSpecificationMapper.selectByExample(litemallGoodsSpecificationExample);
            for (LitemallGoodsSpecification litemallGoodsSpecification : specificationList) {
                CommodityDetailRegualrValueForm commodityDetailRegualrValueForm = new CommodityDetailRegualrValueForm();
                commodityDetailRegualrValueForm.setSpecId(litemallGoodsSpecification.getId());
                commodityDetailRegualrValueForm.setValue(litemallGoodsSpecification.getValue());
                valueList.add(commodityDetailRegualrValueForm);
            }
            commodityDetailRegualrNameForm.setValueList(valueList);
            regualrList.add(commodityDetailRegualrNameForm);
        }
        onlineProductSpec.setRegualrList(regualrList);

        // 组装常规规格商品
        List<CommodityDetailRegualrForm> regualrCombo = new ArrayList<>();
        LitemallGoodsProductExample litemallGoodsProductExample = new LitemallGoodsProductExample();
        litemallGoodsProductExample.createCriteria().andDeletedEqualTo(false)
                .andGoodsIdEqualTo(onlineId)
                .andTypeEqualTo(GoodsProductConstant.TYPE_ONLINE);
        List<LitemallGoodsProduct> litemallGoodsProductList = litemallGoodsProductMapper.selectByExample(litemallGoodsProductExample);
        for (LitemallGoodsProduct product : litemallGoodsProductList) {
            CommodityDetailRegualrForm commodityDetailRegualrForm = new CommodityDetailRegualrForm();
            commodityDetailRegualrForm.setProductId(product.getId());
            commodityDetailRegualrForm.setCost(product.getPrice());
            commodityDetailRegualrForm.setOrginalPrice(product.getOriginalPrice());
            commodityDetailRegualrForm.setDeposit(product.getDeposit());
            commodityDetailRegualrForm.setPicture(product.getUrl());
            commodityDetailRegualrForm.setWeight(product.getWeight());

            List<CommodityDetailRegualrListForm> regualrListForms = new ArrayList<>();
            List<LitemallGoodsProductSpecification> specList = JSON.parseArray(product.getSpecifications(), LitemallGoodsProductSpecification.class);
            for (LitemallGoodsProductSpecification specification : specList) {
                CommodityDetailRegualrListForm regualrListForm = new CommodityDetailRegualrListForm();
                regualrListForm.setSpecId(specification.getId());
                regualrListForm.setName(specification.getInfoName());
                regualrListForm.setValue(specification.getName());
                regualrListForms.add(regualrListForm);
            }
            commodityDetailRegualrForm.setRegualrs(regualrListForms);
            regualrCombo.add(commodityDetailRegualrForm);
        }
        onlineProductSpec.setRegualrCombo(regualrCombo);
        return onlineProductSpec;
    }

    public Object addOnlineServiceCity(OnlineServiceCityVo onlineServiceCityVo){
        AgedmallOnlineCity agedmallOnlineCity;
        //编辑
        if(onlineServiceCityVo.getServicecityId()>0){
            agedmallOnlineCity = agedmallOnlineCityMapper.selectByPrimaryKeySelective(onlineServiceCityVo.getServicecityId());
            AgedmallOnlineCityProductExample cityProductExample=new AgedmallOnlineCityProductExample();
            cityProductExample.or().andOnlineCityIdEqualTo(onlineServiceCityVo.getServicecityId()).andDeletedEqualTo(false);
            List<AgedmallOnlineCityProduct> agedmallOnlineCityProducts = agedmallOnlineCityProductMapper.selectByExampleSelective(cityProductExample);

            List<AgedmallOnlineCityProduct> cityProducts =new ArrayList<>();
            for (int i = 0; i < onlineServiceCityVo.getServiceSpec().size(); i++) {
                for (int j = 0; j < agedmallOnlineCityProducts.size(); j++) {
                    if(onlineServiceCityVo.getServiceSpec().get(i).getServiceSpecId()
                            .equals(agedmallOnlineCityProducts.get(j).getOnlineServerProductId().toString())){
                        AgedmallOnlineCityProduct agedmallOnlineCityProduct=agedmallOnlineCityProducts.get(j);
                        agedmallOnlineCityProduct.setOnlineServerProductId(Long.parseLong(onlineServiceCityVo.getServiceSpec().get(i).getServiceSpecId()));
                        agedmallOnlineCityProduct.setOnlineServerProductPrice(BigDecimal.valueOf(onlineServiceCityVo.getServiceSpec().get(i).getSalePrice()));
                        cityProducts.add(agedmallOnlineCityProduct);
                    }
                }
            }
            agedmallOnlineMapper.updateOnlineCityProductBatchSelective(cityProducts);
        }
        //新增
        else{
            agedmallOnlineCity=new AgedmallOnlineCity();
            AgedmallOnlineCityExample onlineCityExample=new AgedmallOnlineCityExample();
            onlineCityExample.or().andProvinceIdEqualTo(onlineServiceCityVo.getServiceCity().getShengId())
                    .andCityIdEqualTo(onlineServiceCityVo.getServiceCity().getShiId())
                    .andOnlineServerIdEqualTo(onlineServiceCityVo.getServiceId().longValue()).andDeletedEqualTo(false);
            List<AgedmallOnlineCity> agedmallOnlineCities = agedmallOnlineCityMapper.selectByExample(onlineCityExample);
            if(agedmallOnlineCities.size()>0){
                return ResponseUtil.fail(AdminErrorCode.SAME_CITY_IN_ONE_SERVICE.getCode(),
                        AdminErrorCode.SAME_CITY_IN_ONE_SERVICE.getMessage());
            }
        }
        agedmallOnlineCity.setProvinceId(onlineServiceCityVo.getServiceCity().getShengId());
        agedmallOnlineCity.setProvince(onlineServiceCityVo.getServiceCity().getSheng());
        agedmallOnlineCity.setCityId(onlineServiceCityVo.getServiceCity().getShiId());
        agedmallOnlineCity.setCity(onlineServiceCityVo.getServiceCity().getShi());
        agedmallOnlineCity.setDoctorTakeOrderType(onlineServiceCityVo.getDoctorTakeOrderType());
        agedmallOnlineCity.setOnlineServerId(onlineServiceCityVo.getServiceId().longValue());
        agedmallOnlineCity.setAddTime(LocalDateTime.now());
        agedmallOnlineCity.setOnlineServerPrice(onlineServiceCityVo.getAllPrice());
        if(onlineServiceCityVo.getServicecityId()>0){
            agedmallOnlineCityMapper.updateByPrimaryKey(agedmallOnlineCity);
        }
        else{
            agedmallOnlineCityMapper.insertSelective(agedmallOnlineCity);
        }
        List<AgedmallOnlineCityProduct> cityProducts =new ArrayList<>();
        for (int i = 0; i < onlineServiceCityVo.getServiceSpec().size(); i++) {
            AgedmallOnlineCityProduct onlineCityProduct=new AgedmallOnlineCityProduct();
            onlineCityProduct.setAddTime(LocalDateTime.now());
            onlineCityProduct.setOnlineCityId(agedmallOnlineCity.getId());
            onlineCityProduct.setOnlineServerProductId(Long.parseLong(onlineServiceCityVo.getServiceSpec().get(i).getServiceSpecId()));
            onlineCityProduct.setOnlineServerProductPrice(BigDecimal.valueOf(onlineServiceCityVo.getServiceSpec().get(i).getSalePrice()));
            cityProducts.add(onlineCityProduct);
        }
        agedmallOnlineMapper.insertOnlineCityProductBatchSelective(cityProducts);
        return ResponseUtil.ok();
    }

    public Object loadOnlineServiceCity(String type,String id){
        LoadOnlineServiceCityDto loadOnlineServiceCityDto=new LoadOnlineServiceCityDto();
        //新增
        if("0".equals(type)){
            ServiceProductDto onlineServiceDepartment = agedmallOnlineMapper.getOnlineServiceDepartment(Integer.parseInt(id));
            AgedmallOnlineServiceProductExample serviceProductExample=new AgedmallOnlineServiceProductExample();
            serviceProductExample.or().andOnlineServiceIdEqualTo(Integer.parseInt(id)).andDeletedEqualTo(false);
            List<AgedmallOnlineServiceProduct> agedmallOnlineServiceProducts = agedmallOnlineServiceProductMapper.selectByExample(serviceProductExample);
            loadOnlineServiceCityDto.setImgs(onlineServiceDepartment.getImgs());
            loadOnlineServiceCityDto.setName(onlineServiceDepartment.getName());
            loadOnlineServiceCityDto.setDepartmentName(onlineServiceDepartment.getDepartmentName());
            if(!agedmallOnlineServiceProducts.isEmpty()){
                OnlineProductSpec onlineProductSpec=onlineServiceProductAssemble(agedmallOnlineServiceProducts.get(0).getOnlineServiceId());
                if(ObjectUtil.isNotNull(onlineProductSpec)){
                    List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm> regualrList=new ArrayList<>();
                    List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm> regualrCombo=new ArrayList<>();
                    regualrList=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrList()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm.class);
                    regualrCombo=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrCombo()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm.class);
                    loadOnlineServiceCityDto.setRegualrList(regualrList);
                    loadOnlineServiceCityDto.setRegualrCombo(regualrCombo);
                }
            }
            loadOnlineServiceCityDto.setProductDetail(agedmallOnlineServiceProducts);
            loadOnlineServiceCityDto.setDepartmentId(onlineServiceDepartment.getDepartmentId());
            loadOnlineServiceCityDto.setDescriptionList(onlineServiceDepartment.getDescriptionList());
        }
        //编辑
        else{
            AgedmallOnlineCity agedmallOnlineCity = agedmallOnlineCityMapper.selectByPrimaryKey(Integer.parseInt(id));
            ServiceProductDto onlineServiceDepartment = agedmallOnlineMapper.getOnlineServiceDepartment(agedmallOnlineCity.getOnlineServerId().intValue());
            List<OnlineServiceProductDto> onlineCityProductMessage = agedmallOnlineMapper.getOnlineCityProductMessage(Integer.parseInt(id));
            loadOnlineServiceCityDto.setImgs(onlineServiceDepartment.getImgs());
            loadOnlineServiceCityDto.setName(onlineServiceDepartment.getName());
            loadOnlineServiceCityDto.setDepartmentName(onlineServiceDepartment.getDepartmentName());

                OnlineProductSpec onlineProductSpec=onlineServiceProductAssemble(agedmallOnlineCity.getOnlineServerId().intValue());
                if(ObjectUtil.isNotNull(onlineProductSpec)){
                    List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm> regualrList=new ArrayList<>();
                    List<org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm> regualrCombo=new ArrayList<>();
                    regualrList=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrList()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrNameForm.class);
                    regualrCombo=JSON.parseArray(JSON.toJSONString(onlineProductSpec.getRegualrCombo()), org.linlinjava.litemall.db.vo.online.CommodityDetailRegualrForm.class);
                    loadOnlineServiceCityDto.setRegualrList(regualrList);
                    loadOnlineServiceCityDto.setRegualrCombo(regualrCombo);
                }
            loadOnlineServiceCityDto.setProductDetail(onlineCityProductMessage);
            loadOnlineServiceCityDto.setDepartmentId(onlineServiceDepartment.getDepartmentId());
            loadOnlineServiceCityDto.setDescriptionList(onlineServiceDepartment.getDescriptionList());
            loadOnlineServiceCityDto.setCityName(agedmallOnlineCity.getCity());
            loadOnlineServiceCityDto.setCityId(agedmallOnlineCity.getCityId());
            loadOnlineServiceCityDto.setProvinceId(agedmallOnlineCity.getProvinceId());
            loadOnlineServiceCityDto.setProvinceName(agedmallOnlineCity.getProvince());
            loadOnlineServiceCityDto.setOnlineServerPrice(agedmallOnlineCity.getOnlineServerPrice());
            loadOnlineServiceCityDto.setDoctorTakeOrderType(agedmallOnlineCity.getDoctorTakeOrderType());
        }
        return ResponseUtil.ok(loadOnlineServiceCityDto);
    }

    public Object  onlineServiceCityList(OnlineServiceCityListVo onlineServiceCityListVo){
        if(ObjectUtil.isNull(onlineServiceCityListVo.getServiceCity())){
            onlineServiceCityListVo.setServiceCity(new ServiceCity());
        }
        Page page=PageHelper.startPage(onlineServiceCityListVo.getPage(),onlineServiceCityListVo.getLimit());
        List<OnlineServiceDepartmentDto> onlineServiceDepartment = agedmallOnlineMapper
                .getOnlineServiceDepartmentList(onlineServiceCityListVo.getServiceId(),onlineServiceCityListVo.getServiceCity().getShengId()
                        ,onlineServiceCityListVo.getServiceCity().getShiId(),
                        onlineServiceCityListVo.getCityKeyWords());
        Map<String,Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",onlineServiceDepartment);
        return ResponseUtil.ok(map);
    }


    public Object unlinkCityList(UnlinkCityListVo unlinkCityListVo){
        if(ObjectUtil.isNull(unlinkCityListVo.getServiceCityAddress())){
            unlinkCityListVo.setServiceCityAddress(new ServiceCity());
        }
        Page page=PageHelper.startPage(unlinkCityListVo.getPage(),unlinkCityListVo.getLimit());
        List<UnchooseCityBackDto> unchooseCityBackDtos = agedmallOnlineMapper.selectUnchooseCityList(unlinkCityListVo.getServiceId(), unlinkCityListVo.getServiceCityAddress().getShengId(),
                unlinkCityListVo.getServiceCityAddress().getShiId(), unlinkCityListVo.getCityKeyWords());
        Map<String,Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",unchooseCityBackDtos);
        return  ResponseUtil.ok(map);
    }



    public Object cancleOnlineServiceCity(List<Integer> ids){
        for (int i = 0; i < ids.size(); i++) {
            int id=ids.get(i);
            agedmallOnlineCityMapper.deleteByPrimaryKey(id);
            AgedmallOnlineCityProductExample cityProductExample=new AgedmallOnlineCityProductExample();
            cityProductExample.or().andOnlineCityIdEqualTo(id);
            agedmallOnlineCityProductMapper.deleteByExample(cityProductExample);
        }
        return ResponseUtil.ok();
    }

    public Object changeState(ChangeStateVo changeStateVo){
        for (int i = 0; i < changeStateVo.getIdList().size(); i++) {
            AgedmallOnlineService agedmallOnlineService = agedmallOnlineServiceMapper.selectByPrimaryKeySelective(changeStateVo.getIdList().get(i));
            agedmallOnlineService.setStat(changeStateVo.getCommodityState());
            agedmallOnlineServiceMapper.updateByPrimaryKeySelective(agedmallOnlineService);
        }
        return ResponseUtil.ok();
    }

    public Object departmentList(DepartListVo departListVo){
        Page page=PageHelper.startPage(departListVo.getPage(),departListVo.getLimit());
        List<DepartmentListBackDto> departmentList = agedmallOnlineMapper.getDepartmentList();
        Map<String,Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",departmentList);
        return ResponseUtil.ok(map);
    }

    public Object addDepartment(AddDepartmentVo addDepartmentVo){
        AgedmallDepartment agedmallDepartmen=new AgedmallDepartment();
        AgedmallDepartmentExample departmentExample=new AgedmallDepartmentExample();
        departmentExample.or().andNameEqualTo(addDepartmentVo.getDepartmentName()).andDeletedEqualTo(false);
        AgedmallDepartment isUseNameDepartment = agedmallDepartmentMapper.selectOneByExample(departmentExample);
        if(ObjectUtil.isNotNull(isUseNameDepartment)){
            return ResponseUtil.fail(AdminErrorCode.DEPARTMENT_NAME_IS_EXIST.getCode(),AdminErrorCode
            .DEPARTMENT_NAME_IS_EXIST.getMessage());
        }
        agedmallDepartmen.setName(addDepartmentVo.getDepartmentName());
        agedmallDepartmen.setAddTime(LocalDateTime.now());
        agedmallDepartmentMapper.insertSelective(agedmallDepartmen);
        return ResponseUtil.ok();
    }

    public Object deleteDepartment(List<String> ids){
        for (int i = 0; i < ids.size(); i++) {
            int id=Integer.parseInt(ids.get(i));
            AgedmallDoctorInfoExample doctorInfoExample=new AgedmallDoctorInfoExample();
            doctorInfoExample.or().andDepartmentIdEqualTo(Long.parseLong(ids.get(i))).andDeletedEqualTo(false);
            AgedmallDoctorInfo agedmallDoctorInfo = agedmallDoctorInfoMapper.selectOneByExample(doctorInfoExample);
            if(ObjectUtil.isNotNull(agedmallDoctorInfo)){
                return ResponseUtil.fail(AdminErrorCode.DEPARTMENT_IS_CONCAT_DOCTOR.getCode(),
                        AdminErrorCode.DEPARTMENT_IS_CONCAT_DOCTOR.getMessage());
            }
            AgedmallDepartment agedmallDepartment = agedmallDepartmentMapper.selectByPrimaryKeySelective(id);
            agedmallDepartment.setDeleted(true);
            agedmallDepartmentMapper.updateByPrimaryKey(agedmallDepartment);
        }
        return ResponseUtil.ok();
    }

    public Object serviceCity(ShiftTableServiceVo shiftTableServiceVo){
        List<UserAndDoctorCountDto> schedulingUserAndDoctorCount = agedmallOnlineMapper.getSchedulingUserAndDoctorCount(shiftTableServiceVo.getCityId(),
                shiftTableServiceVo.getMonth(),shiftTableServiceVo.getDoctorId());
        return ResponseUtil.ok(schedulingUserAndDoctorCount);
    }


    public Object serviceCityDoctor(ShiftTableServiceVo shiftTableServiceVo){
        List<UserAndDoctorCountDto> doctorSchedulingUserCount = agedmallOnlineMapper.getDoctorSchedulingUserCount(shiftTableServiceVo.getDoctorId(), shiftTableServiceVo.getMonth());
        return ResponseUtil.ok(doctorSchedulingUserCount);
    }

    public Object appointService(AppointServiceVo appointServiceVo){
        List<DoctorConsumeDto> doctorConsumeDtos = agedmallOnlineMapper.selectDoctorConsumeList(
              appointServiceVo.getDocId(),
                appointServiceVo.getCityId()
                ,appointServiceVo.getDate()
                ,appointServiceVo.getNextDate());
        return ResponseUtil.ok(doctorConsumeDtos);
    }


    public Object addDoctor(AddDoctorVo addDoctorVo){
        String password="123456";
        LitemallUser litemallUser;
        AgedmallDoctorInfo agedmallDoctorInfo;
        String changePhone="";
        AgedmallWechatGroup wechatGroup;
        Integer groupId;

        //判断群人数
        String[] members=addDoctorVo.getGroupMembers().split(",");
        List<String> membersList=new ArrayList<>();
        Collections.addAll(membersList,members);
        boolean isExist=membersList.contains(addDoctorVo.getGroupManager());
        if(!isExist){
            membersList.add(addDoctorVo.getGroupManager());
        }
        if(membersList.size()<2){
            return ResponseUtil.fail(1200,"群成员人数必须大于2个");
        }

        List<String> addMembers=new ArrayList<>();;
        List<String> delMembers=new ArrayList<>();;
        if(addDoctorVo.getDoctorId()!=null){
            agedmallDoctorInfo = agedmallDoctorInfoMapper.selectByPrimaryKey(addDoctorVo.getDoctorId().longValue());
            litemallUser=litemallUserMapper.selectByPrimaryKey(agedmallDoctorInfo.getUserId().intValue());
            changePhone=litemallUser.getUsername();
            wechatGroup=agedmallWechatGroupMapper.selectByPrimaryKey(agedmallDoctorInfo.getWechatGroupId());
            groupId=wechatGroup.getGroupId();
            //前端的成员
            String[] nowMembers=addDoctorVo.getGroupMembers().split(",");
            List<String> nowMembersList=new ArrayList<>();
            Collections.addAll(nowMembersList,nowMembers);
            //原来的成员
            String[] oldMembers=wechatGroup.getGroupMembers().split(",");
            List<String> oldMembersList=new ArrayList<>();
            Collections.addAll(oldMembersList,oldMembers);
            //需要删除的成员
            for (int i = 0; i < oldMembersList.size(); i++) {
                if(!nowMembersList.contains(oldMembersList.get(i))){
                    delMembers.add(oldMembersList.get(i));
                }
            }
            //需要新增的成员
            for (int i = 0; i < nowMembersList.size(); i++) {
                if(!oldMembersList.contains(nowMembersList.get(i))){
                    addMembers.add(nowMembersList.get(i));
                }
            }
        }
        else{
            agedmallDoctorInfo=new AgedmallDoctorInfo();
            wechatGroup=new AgedmallWechatGroup();
            AgedmallWechatGroupNumber groupNumber=new AgedmallWechatGroupNumber();
            agedmallWechatGroupNumberMapper.insert(groupNumber);
            groupId=groupNumber.getId();
        }
        //添加user表
        LitemallUserExample userExample=new LitemallUserExample();
        userExample.or().andMobileEqualTo(addDoctorVo.getPhone());
        litemallUser = litemallUserMapper.selectOneByExample(userExample);
        if(ObjectUtil.isNull(litemallUser)){
            litemallUser=new LitemallUser();
            litemallUser.setUsername(addDoctorVo.getPhone());
            litemallUser.setNickname(addDoctorVo.getDoctorName());
            litemallUser.setMobile(addDoctorVo.getPhone());
        }
//        if(litemallUsers.size()>0&&!changePhone.equals(addDoctorVo.getPhone())){
//            return ResponseUtil.fail(AdminErrorCode.PHONE_CODE_IS_EXIST.getCode(),
//                    AdminErrorCode.PHONE_CODE_IS_EXIST.getMessage());
//        }






        String groupName=addDoctorVo.getGroupName().length()>51?
                addDoctorVo.getGroupName().substring(0,51):addDoctorVo.getGroupName();
        wechatGroup.setGroupName(groupName);
        wechatGroup.setGroupManager(addDoctorVo.getGroupManager());
        wechatGroup.setGroupMembers(addDoctorVo.getGroupMembers());
        wechatGroup.setGroupId(groupId);
        wechatGroup.setAddTime(LocalDateTime.now());

        if(litemallUser.getId()==null){
            litemallUser.setPassword(BcryptUtil.encode(password));
            litemallUser.setGender((byte) 0);
            litemallUser.setUserLevel((byte) 0);
            litemallUser.setStatus((byte) 0);
            litemallUser.setAddTime(LocalDateTime.now());
            litemallUserMapper.insertSelective(litemallUser);
        }
        else{
            litemallUserMapper.updateByPrimaryKey(litemallUser);
        }
        if(addDoctorVo.getDoctorId()!=null){

            agedmallWechatGroupMapper.updateByPrimaryKeySelective(wechatGroup);
        }
        else{

            agedmallWechatGroupMapper.insertSelective(wechatGroup);
        }
        //添加代理人表
        if(addDoctorVo.getDoctorId()==null) {
            AgedmallAgent agedmallAgent = new AgedmallAgent();
            agedmallAgent.setUserId(litemallUser.getId());
            agedmallAgent.setType((byte) 2);
            agedmallAgent.setAddTime(LocalDateTime.now());
            agedmallAgentMapper.insertSelective(agedmallAgent);
        }
        //添加医生表

        agedmallDoctorInfo.setHospitalName(addDoctorVo.getHospital());
        agedmallDoctorInfo.setDoctorName(addDoctorVo.getDoctorName());
        agedmallDoctorInfo.setDepartmentId(addDoctorVo.getDepartment().longValue());
        agedmallDoctorInfo.setBusId(addDoctorVo.getShopId());
        agedmallDoctorInfo.setOnlineService(addDoctorVo.getServiceId());
        agedmallDoctorInfo.setAddTime(LocalDateTime.now());
        agedmallDoctorInfo.setWechatId(addDoctorVo.getStaffWechatName());
        agedmallDoctorInfo.setWechatGroupId(wechatGroup.getId());
//        AgedmallTimeTemplate agedmallTimeTemplate = agedmallTimeTemplateMapper.selectByPrimaryKeySelective(addDoctorVo.getServiceTime().longValue());
//        if(ObjectUtil.isNull(agedmallTimeTemplate)){
//            return ResponseUtil.fail(AdminErrorCode.SERIVCE_TIME_TEMPLATE_NOT_NULL.getCode(),AdminErrorCode.SERIVCE_TIME_TEMPLATE_NOT_NULL.getMessage());
//        }
//        agedmallDoctorInfo.setServiceTimeTemplate(toJSONString(agedmallTimeTemplate));
        if(addDoctorVo.getDoctorId()!=null) {

            agedmallDoctorInfoMapper.updateByPrimaryKey(agedmallDoctorInfo);
            UpdateGroupMessage updateGroupMessage=new UpdateGroupMessage();
            updateGroupMessage.setChatId(wechatGroup.getGroupId().toString());
            updateGroupMessage.setName(wechatGroup.getGroupName());
            updateGroupMessage.setOwner(wechatGroup.getGroupManager());
            updateGroupMessage.setAddUserList(addMembers);
            updateGroupMessage.setDelUserList(delMembers);
            String result=HttpRequest.post(serverAddress.getCorp()+"message/updateGroupChat")
                    .body(JSON.toJSONString(updateGroupMessage))
                    .timeout(50000)
                    .execute().body();
            return getResultMessage(result);
        }
        else{
            agedmallDoctorInfo.setUserId(litemallUser.getId().longValue());
            agedmallDoctorInfoMapper.insertSelective(agedmallDoctorInfo);

            GroupMessage groupMessage=new GroupMessage();
            groupMessage.setName(groupName);
            groupMessage.setManagerName(addDoctorVo.getGroupManager());
            groupMessage.setUserList(membersList);
            groupMessage.setChatId(wechatGroup.getGroupId().toString());
            String result=HttpRequest.post(serverAddress.getCorp()+"message/createGroupChat")
                    .body(JSON.toJSONString(groupMessage))
                    .timeout(50000)
                    .execute().body();
            return getResultMessage(result);
        }
    }


    public Object deleteDoctor(List<String> ids){
        List<Long> idList=new ArrayList<>();
        for (int i = 0; i < ids.size(); i++) {
            Long id=Long.parseLong(ids.get(i));
            idList.add(id);
        }
        AgedmallDoctorInfoExample doctorInfoExample=new AgedmallDoctorInfoExample();
        doctorInfoExample.or().andIdIn(idList);
        List<AgedmallDoctorInfo> agedmallDoctorInfos = agedmallDoctorInfoMapper.selectByExample(doctorInfoExample);
        List<Integer> userIdList=new ArrayList<>();
        for (int i = 0; i < agedmallDoctorInfos.size(); i++) {
            userIdList.add(agedmallDoctorInfos.get(i).getUserId().intValue());
        }
        if(userIdList.size()>0){
            LitemallUserExample userExample=new LitemallUserExample();
            userExample.or().andIdIn(userIdList);
            litemallUserMapper.logicalDeleteByExample(userExample);
//        agedmallOnlineMapper.deleteAgentByUserId(userIdList);
        AgedmallAgentExample agedmallAgentExample=new AgedmallAgentExample();
        agedmallAgentExample.or().andUserIdIn(userIdList);
        agedmallAgentMapper.logicalDeleteByExample(agedmallAgentExample);
        }
        agedmallDoctorInfoMapper.logicalDeleteByExample(doctorInfoExample);
        return ResponseUtil.ok();
    }

    public Object addServiceTime(AddServiceTimeVo addServiceTimeVo){
        AgedmallTimeTemplate agedmallTimeTemplate=new AgedmallTimeTemplate();
        AgedmallTimeTemplateExample timeTemplateExample=new AgedmallTimeTemplateExample();
        timeTemplateExample.or().andTemplateNameEqualTo(addServiceTimeVo.getTimeModelName()).andDeletedEqualTo(false);
        AgedmallTimeTemplate isUseTemplateName = agedmallTimeTemplateMapper.selectOneByExample(timeTemplateExample);
        if(ObjectUtil.isNotNull(isUseTemplateName)){
            return ResponseUtil.fail(AdminErrorCode.SERVICE_TIME_NAME_IS_EXIST.getCode(),
                    AdminErrorCode.SERVICE_TIME_NAME_IS_EXIST.getMessage());
        }
        agedmallTimeTemplate.setTemplateName(addServiceTimeVo.getTimeModelName());
        agedmallTimeTemplate.setAppointmentDay(Integer.parseInt(addServiceTimeVo.getAppointDay()));
        agedmallTimeTemplate.setServiceTime(toJSONString(addServiceTimeVo.getTimeList()));
        agedmallTimeTemplate.setAddTime(LocalDateTime.now());
        agedmallTimeTemplate.setBusId(addServiceTimeVo.getShopId().longValue());
        agedmallTimeTemplateMapper.insertSelective(agedmallTimeTemplate);
        return ResponseUtil.ok();
    }


    public Object doctorList(DoctorListVo doctorListVo){
        Page page=PageHelper.startPage(doctorListVo.getPage(),doctorListVo.getLimit());
        if(ObjectUtil.isNull(doctorListVo.getAddress())){
            doctorListVo.setAddress(new ServiceCity());
        }
        List<DoctorMessageDto> onlineServiceDtos = agedmallOnlineMapper.selectHospitalList(doctorListVo.getShopId(),doctorListVo.getAddress().getShengId(),
                doctorListVo.getAddress().getShiId(),
                doctorListVo.getKeyword(),doctorListVo.getDeptId());

        for (int i = 0; i < onlineServiceDtos.size(); i++) {
            String[] onlineService=onlineServiceDtos.get(i).getOnlineService().split(",");
            List<Integer> parse=new ArrayList<>();
            for (int j = 0; j < onlineService.length; j++) {
                parse.add(Integer.parseInt(onlineService[j]));
            }
            List<ServiceCityListSaveDto> serviceCityListByIdList = agedmallOnlineMapper.getServiceCityListByIdList(parse);
            onlineServiceDtos.get(i).setServiceCityListSaveDtos(serviceCityListByIdList);
        }
        Map<String, Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",onlineServiceDtos);
        return ResponseUtil.ok(map);
    }

    public Object serviceCountList(Integer docId){
        List<DoctorConsumeDto> doctorConsumeDtos = agedmallOnlineMapper.selectDoctorConsumeList(docId,null,null,null);
        return ResponseUtil.ok(doctorConsumeDtos);
    }


    public Object getServiceByCityId(SearchServiceByCityVo searchServiceByCityVo){
        Page page=PageHelper.startPage(searchServiceByCityVo.getPage(),searchServiceByCityVo.getLimit());
        List<ServiceCityBackDto> serviceCityBackDtos = agedmallOnlineMapper.selectServiceListByCityId(searchServiceByCityVo.getCityId(),
                searchServiceByCityVo.getKeywords(),searchServiceByCityVo.getShopId(),searchServiceByCityVo.getDepartmentId());
        Map<String, Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",serviceCityBackDtos);
        return ResponseUtil.ok(map);
    }

    public Object getServiceTimeList(ServiceTimeVo serviceTimeVo){
        Page page=PageHelper.startPage(serviceTimeVo.getPage(),serviceTimeVo.getLimit());
        List<AgedmallTimeTemplate> agedmallTimeTemplates = agedmallOnlineMapper.selectTimeTemplateList(serviceTimeVo.getShopId(),serviceTimeVo.getKeywords());
        Map<String, Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",agedmallTimeTemplates);
        return ResponseUtil.ok(map);
    }


    public Object getClassByService(Integer shopId){
        List<AgedmallClassify> agedmallClassifies = agedmallOnlineMapper.selectClassifyByService(shopId);

        List<AgedmallClassify> childrenClassify =new ArrayList<>();
        List<AgedmallClassify> parentClassify = new ArrayList<>();
        for (int i = 0; i < agedmallClassifies.size(); i++) {

                childrenClassify.add(agedmallClassifies.get(i));
                AgedmallClassifyExample classifyExample=new AgedmallClassifyExample();
                classifyExample.or().andIdEqualTo(agedmallClassifies.get(i).getPid());
                List<AgedmallClassify> fatherClasses = agedmallClassifyMapper.selectByExample(classifyExample);
                parentClassify.add(fatherClasses.get(0));

        }
        List<ClassifyParent> backParents=new ArrayList<>();
        for (int i = 0; i < parentClassify.size(); i++) {
            ClassifyParent classifyParent=new ClassifyParent();
            List<ClassiftChilden> childens=new ArrayList<>();
            for (int j = 0; j < childrenClassify.size(); j++) {
                if(childrenClassify.get(j).getPid().equals(parentClassify.get(i).getId())){
                    ClassiftChilden classiftChilden=new ClassiftChilden();
                    classiftChilden.setLabel(childrenClassify.get(j).getName());
                    classiftChilden.setValue(childrenClassify.get(j).getId());
                    childens.add(classiftChilden);
                }
            }
            classifyParent.setLabel(parentClassify.get(i).getName());
            classifyParent.setValue(parentClassify.get(i).getId());
            classifyParent.setChildren(childens);
            backParents.add(classifyParent);
        }
        return ResponseUtil.ok(backParents);
    }


    public  Object loadDoctorDate(Integer serviceId){
        AgedmallOnlineService agedmallOnlineService = agedmallOnlineServiceMapper.selectByPrimaryKey(serviceId);
        Map<String,Object> backMap=new HashMap<>();
        List<String> appointmentDay=new ArrayList<>();
        String today = DateUtil.today();
        Date todayDate = DateUtil.date(System.currentTimeMillis());
        appointmentDay.add(today);
        //推移时间
        for (int i = 0; i < agedmallOnlineService.getAppointmentDay(); i++) {
            DateTime dates = DateUtil.offsetDay(todayDate, 1);
            String format = DateUtil.format(dates, "yyyy-MM-dd");
            appointmentDay.add(format);
            todayDate=dates;
        }
        backMap.put("days",appointmentDay);
        backMap.put("timeRange",agedmallOnlineService.getServiceTime());
        return ResponseUtil.ok(backMap);
    }


    public Object descriptDoctorList( DescriptDoctorListVo descriptDoctorListVo){
        String[] timeRangeArray=descriptDoctorListVo.getTimeRange().split("-");
        Date day = DateUtil.parse(descriptDoctorListVo.getDate());
        Date startTime=DateUtil.parse(descriptDoctorListVo.getDate()+" "+timeRangeArray[0]);
        Date endTime=DateUtil.parse(descriptDoctorListVo.getDate()+" "+timeRangeArray[1]);
        ZoneId zoneId = ZoneId.systemDefault();
        Page page=PageHelper.startPage(descriptDoctorListVo.getPage(),descriptDoctorListVo.getLimit());
        List<ChangeDoctorBackDto> changeDoctorBackDtos = agedmallOnlineMapper.selectChangeDoctorList(LocalDateTime.ofInstant(day.toInstant(), zoneId),
                LocalDateTime.ofInstant(startTime.toInstant(), zoneId), LocalDateTime.ofInstant(endTime.toInstant(), zoneId), descriptDoctorListVo.getServiceCityId(),
                descriptDoctorListVo.getDoctorName(),
                descriptDoctorListVo.getDpartmentId());
        Map<String, Object> map=new HashMap<>();
        map.put("total",page.getTotal());
        map.put("data",changeDoctorBackDtos);
        return ResponseUtil.ok(map);
    }


    public  Object getInfo(OnlineServiceInfoVo  onlineServiceInfoVo){
        AgedmallOnlineService agedmallOnlineService = agedmallOnlineServiceMapper.selectByPrimaryKey(onlineServiceInfoVo.getServiceId());
        OnlineServiceInfoDto onlineServiceInfoDto=new OnlineServiceInfoDto();
        onlineServiceInfoDto.setServiceId(agedmallOnlineService.getId());
        onlineServiceInfoDto.setServiceName(agedmallOnlineService.getName());
        onlineServiceInfoDto.setServiceImage(agedmallOnlineService.getServiceImage());
        return ResponseUtil.ok(onlineServiceInfoDto);
    }


}
